package net.dgg.iboss.sc.backservice.task.service;/**
 * Created by Administrator on 2018/5/24.
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import net.dgg.iboss.base.service.CmsService;
import net.dgg.iboss.base.util.DateUtil;
import net.dgg.iboss.sc.backservice.task.constant.ScProductConstant;
import net.dgg.iboss.sc.backservice.task.dao.ProductOrderDao;
import net.dgg.iboss.sc.backservice.task.dao.ProductTimeStatusDao;
import net.dgg.iboss.sc.backservice.task.entity.Node;
import net.dgg.iboss.sc.backservice.task.entity.ProductOrder;
import net.dgg.iboss.sc.backservice.task.entity.ProductTimeStatus;
import net.dgg.iboss.sc.backservice.task.entity.UserEntity;
import net.dgg.iboss.sc.backservice.task.util.MQMessageSendUtil;
import net.dgg.iboss.sc.backservice.task.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.*;

/**
 * <p>@Title 生产定时器Service</p>
 * <p>@Description 办理中相关</p>
 * <p>@Version 1.0.0 版本号</p>
 * <p>@author maoquanyi</p>
 * <p>@date 2018年08月17日</p>
 * <p>Copyright © dgg group.All Rights Reserved. 版权信息</p>
 */
@Service
public class ProductOrderService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private CmsService cmsService;

    //新的dao
    @Autowired
    private ProductOrderDao productOrderDao;
    @Autowired
    private ProductTimeStatusDao productTimeStatusDao;
    @Resource
    private CommonService commonService;
    @Resource
    private UserService userService;
    @Resource
    private FlowService flowService;

    /**
    * <p>@Description 更新分配超期状态</p>
    * <p>@author mqy</p>
    * <p>@Time 2018/8/17 0017 16:05 创建时间</p>
    * <p>@return</p>
    */
    @Transactional
    public void updateAllotTimeStatusAndSendMsg() {
        //查询分配超期
        List<ProductTimeStatus> productTimeStatusList = this.productTimeStatusDao.query(new HashMap<String,Object>() {{
            put("distributionEndTime", "true");
            put("statusArr", new String[]{ScProductConstant.SC_TO_RECEIVE_XDDJS, ScProductConstant.SC_ORDER_BACK_TO_ALLOT});
            put("distributionTimeOutStatus", ScProductConstant.TIME_OUT);
        }});
        if (productTimeStatusList.size() == 0) {
            return;
        }
        List<Long> idList = new ArrayList<>(productTimeStatusList.size());
        for (ProductTimeStatus productTimeStatus : productTimeStatusList) {
            idList.add(productTimeStatus.getId());
        }
        //满足条件的全部改为分配超期
        this.productTimeStatusDao.updateDistributionTimeOutStatus(ScProductConstant.TIME_OUT, idList);
    }




    /**
    * <p>@Description 更新接收超期状态并发送消息</p>
    * <p>@author mqy</p>
    * <p>@Time 2018/9/5 0005 16:27 创建时间</p>
    * <p>@return</p>
    */
    @Transactional
    public void updateReceiveTimeStatus() {
        List<ProductTimeStatus> scProductTimeStatusList = this.productTimeStatusDao.query(new HashMap<String,Object>() {{
            put("receiveEndTimeOut", "true");
            // put("flag", "1");  注释掉是因为会导致暂停后 转单移交 到待接收时状态无法更新
            put("receiveTimeStatusNotEq", ScProductConstant.TIME_OUT);
        }});
        if (scProductTimeStatusList.size() == 0) {
            return;
        }
        final List<Long> idList = new ArrayList<>(scProductTimeStatusList.size());
        Map<Long, ProductTimeStatus> scProductTimeStatusMap = new HashMap<>(scProductTimeStatusList.size());
        for (ProductTimeStatus scProductTimeStatus : scProductTimeStatusList) {
            idList.add(scProductTimeStatus.getId());
            scProductTimeStatusMap.put(scProductTimeStatus.getId(), scProductTimeStatus);
        }
        this.productTimeStatusDao.updateReceiveTimeStatus(ScProductConstant.TIME_OUT, idList);
        List<ProductOrder> scProductOrderList = this.productOrderDao.queryProductOrder(new HashMap<String,Object>() {{
            put("idInList", idList);
        }});
        // 流程人员
        List<String> flowStatus = new ArrayList<String>() {{
            add(ScProductConstant.SC_TO_RECEIVE_XDDJS);// 下单待接收
            add(ScProductConstant.SC_TO_RECEIVE_FPDJS);// 分配待接收
            add(ScProductConstant.SC_TO_RECEIVE_TDDJS);// 退回待接收
        }};
        // 代接收人员
        List<String> waitReceiveStatus = new ArrayList<String>() {{
            add(ScProductConstant.SC_TO_RECEIVE_ZDDJS); // 转单待接收
            add(ScProductConstant.SC_TO_RECEIVE_YJDJS); // 移交待接收
        }};
        try {
            for (ProductOrder scProductOrder : scProductOrderList) {
                Long receiverId = flowStatus.contains(scProductOrder.getStatus()) ? scProductOrder.getFlowUserId()
                        : (waitReceiveStatus.contains(scProductOrder.getStatus()) ? scProductOrder.getWaitingReceiverId() : null);
                if (receiverId == null) {
                    continue;
                }
                ProductTimeStatus scProductTimeStatus = scProductTimeStatusMap.get(scProductOrder.getId());
                if (scProductTimeStatus == null) {
                    continue;
                }
                List<UserEntity> users = new ArrayList<>();
                users.add( userService.findUserById(scProductOrder.getFlowUserId()));
                String[] msg = new String[]{scProductOrder.getScProductOrderNo(), DateUtil.dateToString(scProductTimeStatus.getReceiveEndTime(), "yyyy-MM-dd HH:mm:ss")};
                commonService.sendMsg(users, msg, "ZZSC_SC_RECEIVE_TIME_EXPIRE");//接收超期
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("生产子订单接收超期消息发送失败！");
        }


    }




    /**
    * <p>@Description 更新订单超期状态并发送消息</p>
    * <p>@author mqy</p>
    * <p>@Time 2018/9/5 0005 16:45 创建时间</p>
    * <p>@return</p>
    */
    @Transactional
    public void updateOrderTimeStatus() {
        List<String> statusArr = new ArrayList<>();
        statusArr.add("ZZSC_STATE_SCPROORDER_CODE1");
        statusArr.add("ZZSC_STATE_SCPROORDER_CODE2");
        statusArr.add("ZZSC_STATE_SCPROORDER_CODE3");
        statusArr.add("ZZSC_STATE_SCPROORDER_CODE4");
        statusArr.add("ZZSC_STATE_SCPROORDER_CODE5");
        statusArr.add("ZZSC_STATE_SCPROORDER_CODE6");
        statusArr.add("ZZSC_STATE_SCPROORDER_CODE14");
        statusArr.add("ZZSC_STATE_SCPROORDER_CODE17");
        List<ProductTimeStatus> scProductTimeStatusList = this.productTimeStatusDao.query(new HashMap<String,Object>() {{
            put("orderEndTimeOut", "true");
            put("flag", "1");
            put("orderTimeStatusNotEq", ScProductConstant.TIME_OUT);
            put("statusArr",statusArr);
        }});
        if (scProductTimeStatusList.size() == 0) {
            return;
        }
        final List<Long> idList = new ArrayList<>(scProductTimeStatusList.size());
        Map<Long, ProductTimeStatus> scProductTimeStatusMap = new HashMap<>(scProductTimeStatusList.size());
        for (ProductTimeStatus scProductTimeStatus : scProductTimeStatusList) {
            idList.add(scProductTimeStatus.getId());
            scProductTimeStatusMap.put(scProductTimeStatus.getId(), scProductTimeStatus);
        }
        this.productTimeStatusDao.updateOrderTimeStatus(ScProductConstant.TIME_OUT, idList);
        List<ProductOrder> scProductOrderList = this.productOrderDao.queryProductOrder(new HashMap<String,Object>() {{
            put("idInList", idList);
        }});
        try {
            for (ProductOrder scProductOrder : scProductOrderList) {
                ProductTimeStatus scProductTimeStatus = scProductTimeStatusMap.get(scProductOrder.getId());
                if (scProductOrder.getFlowUserId() == null || scProductTimeStatus == null) {
                    continue;
                }
                //生产单号,客户名称,产品名称,超期天数,合同日期
                int day = DateUtil.daysBetween( scProductTimeStatus.getOrderEndTime(),new Date())+1;
                String[] msg = new String[]{scProductOrder.getScProductOrderNo(),scProductOrder.getCustomerName(),
                        scProductOrder.getProductName(),String.valueOf(day), DateUtil.dateToString(scProductOrder.getContractEndDate(), "yyyy-MM-dd")};
                sendMsg(scProductOrder,msg,"ZZSC_SC_ORDER_TIME_EXPIRE");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("生产订单订单超期消息发送失败！");
        }
    }



    /**
    * <p>@Description 更新预计开启时间超期状态并发送消息</p>
    * <p>@author mqy</p>
    * <p>@Time 2018/9/5 0005 16:53 创建时间</p>
    * <p>@return</p>
    */
    @Transactional
    public void updateExpectOpenTimeStatus() {
        //预计开启时间和超期状态
        List<ProductTimeStatus> scProductTimeStatusList = this.productTimeStatusDao.query(new HashMap<String,Object>() {{
            put("expectOpenDateOut", "true");
            put("expectOpenTimeStatusNotEq", ScProductConstant.TIME_OUT);
        }});
        if (scProductTimeStatusList.size() == 0) {
            return;
        }
        final List<Long> idList = new ArrayList<>(scProductTimeStatusList.size());
        Map<Long, ProductTimeStatus> scProductTimeStatusMap = new HashMap<>(scProductTimeStatusList.size());
        for (ProductTimeStatus scProductTimeStatus : scProductTimeStatusList) {
            idList.add(scProductTimeStatus.getId());
            scProductTimeStatusMap.put(scProductTimeStatus.getId(), scProductTimeStatus);
        }
        this.productTimeStatusDao.updateExpectOpenTimeStatus(ScProductConstant.TIME_OUT, idList);
        List<ProductOrder> scProductOrderList = this.productOrderDao.queryProductOrder(new HashMap<String,Object>() {{
            put("idInList", idList);
        }});

        try {
            for (ProductOrder scProductOrder : scProductOrderList) {
                ProductTimeStatus scProductTimeStatus = scProductTimeStatusMap.get(scProductOrder.getId());
                if (scProductOrder.getFlowUserId() == null || scProductTimeStatus == null) {
                    continue;
                }
                List<UserEntity> users = new ArrayList<>();
                users.add( userService.findUserById(scProductOrder.getFlowUserId()));
                String[] msg = new String[]{scProductOrder.getScProductOrderNo(), DateUtil.dateToString(scProductTimeStatus.getExpectOpenDate(), "yyyy-MM-dd HH:mm:ss")};
                commonService.sendMsg(users, msg, "ZZSC_SC_EXPECT_TIME_COME");//预计开启时间
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("生产订单预计开启时间超期消息发送失败！");
        }
    }

    @Transactional
    public void updateStopOrder() {
        int num;
        //查询多少天的订单需要进入中止库
        Map maps = commonService.getTreeBookObj("ZZSC_STOP_ORDER_NUMBER");
        if(maps==null||maps.get("ext1")==null || "".equals(maps.get("ext1").toString())){
            num = 180;
        }else {
            num = Integer.parseInt(maps.get("ext1").toString());
        }
        List<ProductOrder> productOrders = productOrderDao.selectStopOrder(num);
        if (productOrders==null || productOrders.size() == 0) {
            return;
        }
        List<Long> ids = new ArrayList<>();
        //将状态设为中止状态
        for(ProductOrder productOrder:productOrders){
            ids.add(productOrder.getId());
        }
        if(ids!=null&&ids.size()>0){
            productOrderDao.updateStatusByIds(ScProductConstant.SC_ORDER_STOP,ids);
        }

        String msgConent="";
        for(ProductOrder productOrder:productOrders){
            List<UserEntity> users = new ArrayList<>();
            if(productOrder.getFlowUserId()!=null){
                //流程人员
                users.add( userService.findUserById(productOrder.getFlowUserId()));
            }
            if(productOrder.getProductUserId()!=null){
                //生产负责人
                users.add( userService.findUserById(productOrder.getProductUserId()));
            }
            String[] msg = new String[]{productOrder.getScProductOrderNo(),productOrder.getCustomerName(),productOrder.getProductName(),String.valueOf(num)};
            if(ScProductConstant.SC_ORDER_IN_PROCESS.equals(productOrder.getStatus())){//办理中
                commonService.sendMsg(users, msg, "ZZSC_SC_IN_PROCESS_STOP");
            }else{
                commonService.sendMsg(users, msg, "ZZSC_SC_SUSPEND_STOP");
            }
            msgConent="您好，您的客户"+productOrder.getCustomerName()+"订单"+productOrder.getOrderNo()+"办理的"
                    +productOrder.getScProductOrderNo()+"业务，订单已中止,请及时确认处理";
            commonService.sendQgjMessage(productOrder.getOrderId(),productOrder.getBusinessTypeCode(),1L,"IBOSS系统管理员","jrcrm_admin",msgConent);
            //提交之后，将订单信息同步到企大顺生产中心
            Map user = cmsService.findUser(1L);
            if(null != user){
                UserEntity userEntity = JSONObject.parseObject(JSON.toJSONString(user), UserEntity.class);
                MQMessageSendUtil.qdsMessageSend(productOrder, null, userEntity);
            }
        }
        //办理中：您好，生产订单{生产订单编号}{客户名称}{订单产品}，已x天未更新进度，订单状态变更为中止订单，请在中止订单页面核实处理。
        //暂停：您好，生产订单{生产订单编号}{客户名称}{订单产品}，已暂停x天，订单状态变更为中止订单，请在中止订单页面核实处理。
    }

    @Transactional
    public void updateContractTimeStatus() {
        List<String> statusArr = new ArrayList<>();
        statusArr.add("ZZSC_STATE_SCPROORDER_CODE1");
        statusArr.add("ZZSC_STATE_SCPROORDER_CODE2");
        statusArr.add("ZZSC_STATE_SCPROORDER_CODE3");
        statusArr.add("ZZSC_STATE_SCPROORDER_CODE4");
        statusArr.add("ZZSC_STATE_SCPROORDER_CODE5");
        statusArr.add("ZZSC_STATE_SCPROORDER_CODE6");
        statusArr.add("ZZSC_STATE_SCPROORDER_CODE14");
        List<ProductTimeStatus> scProductTimeStatusList = this.productTimeStatusDao.query(new HashMap<String,Object>() {{
            put("contractEndTimeOut", "true");
            put("statusArr",statusArr);
            put("contractTimeStatusNotEq", ScProductConstant.TIME_OUT);
        }});
        if (scProductTimeStatusList.size() == 0) {
            return;
        }
        final List<Long> idList = new ArrayList<>(scProductTimeStatusList.size());
        Map<Long, ProductTimeStatus> scProductTimeStatusMap = new HashMap<>(scProductTimeStatusList.size());
        for (ProductTimeStatus scProductTimeStatus : scProductTimeStatusList) {
            idList.add(scProductTimeStatus.getId());
            scProductTimeStatusMap.put(scProductTimeStatus.getId(), scProductTimeStatus);
        }
        this.productTimeStatusDao.updateContractTimeStatus(ScProductConstant.TIME_OUT, idList);
        List<ProductOrder> scProductOrderList = this.productOrderDao.queryProductOrder(new HashMap<String,Object>() {{
            put("idInList", idList);
        }});
        try {
            for (ProductOrder scProductOrder : scProductOrderList) {
                if (scProductOrder.getFlowUserId() == null) {
                    return;
                }
                //生产单号,客户名称,产品名称,超期天数,合同日期
                int day = DateUtil.daysBetween(scProductOrder.getContractEndDate(),new Date());
                String[] msg = new String[]{scProductOrder.getScProductOrderNo(),scProductOrder.getCustomerName(),scProductOrder.
                        getProductName(),String.valueOf(day), DateUtil.dateToString(scProductOrder.getContractEndDate(), "yyyy-MM-dd")};
                sendMsg(scProductOrder,msg,"ZZSC_SC_CONTRACT_TIME_EXPIRE");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("生产订单合同超期消息发送失败！");
        }
    }

    /**
     * 发送消息
     * @param scProductOrder
     * @param msg
     * @param templateCode
     */
    private void sendMsg(ProductOrder scProductOrder,String[] msg,String templateCode){
        List<UserEntity> users = new ArrayList<>();
        //签单商务
        UserEntity signUser = userService.findUserById(scProductOrder.getSignUserId());
        if(signUser!=null){
            users.add(signUser);
        }
        //商务经理
        String[] codes = new String[]{"SWJL"};
        List<UserEntity> signUsers = userService.findUserByRoleCodesAndOrgs(codes, 0, scProductOrder.getSignUserOrgId());
        if(signUsers!=null && signUsers.size()>0){
            users.addAll(signUsers);
        }
        if(scProductOrder.getFlowUserId()!=null){
            //流程人员
            users.add( userService.findUserById(scProductOrder.getFlowUserId()));
            //后台经理
            String[] flowCodes = new String[]{"ZZSC_HTMANAGER"};
            if(scProductOrder.getFlowUserOrgId()!=null){
                List<UserEntity> flowUser = userService.findUserByRoleCodesAndOrgs(flowCodes, 0, scProductOrder.getFlowUserOrgId());
                if(flowUser!=null && flowUser.size()>0) {
                    users.addAll(flowUser);
                }
            }
        }
        commonService.sendMsg(users, msg, templateCode);
    }

    public void nodeAlert() {
        List<String> statusArr = new ArrayList<>();
        statusArr.add("ZZSC_STATE_SCPROORDER_CODE1");
        statusArr.add("ZZSC_STATE_SCPROORDER_CODE2");
        statusArr.add("ZZSC_STATE_SCPROORDER_CODE3");
        statusArr.add("ZZSC_STATE_SCPROORDER_CODE4");
        statusArr.add("ZZSC_STATE_SCPROORDER_CODE5");
        statusArr.add("ZZSC_STATE_SCPROORDER_CODE6");
        statusArr.add("ZZSC_STATE_SCPROORDER_CODE14");
        //查询节点即将超期(节点办理截止时间小于1小时)订单信息,
        List<ProductTimeStatus> scProductTimeStatusList = this.productTimeStatusDao.query(new HashMap<String,Object>() {{
            put("nodeAlert", "true");
            put("statusArr",statusArr);
        }});
        if (scProductTimeStatusList.size() == 0) {
            return;
        }
        final List<Long> idList = new ArrayList<>(scProductTimeStatusList.size());
        for (ProductTimeStatus scProductTimeStatus : scProductTimeStatusList) {
            idList.add(scProductTimeStatus.getId());
        }
        List<ProductOrder> scProductOrderList = this.productOrderDao.queryProductOrder(new HashMap<String,Object>() {{
            put("idInList", idList);
        }});
        new Thread() {
            public void run() {
                for (ProductOrder scProductOrder : scProductOrderList) {
                    if (scProductOrder.getFlowUserId() == null) {
                        continue;
                    }
                    //生产单号,客户名称,产品名称,节点名称
                    String[] msg = new String[]{scProductOrder.getScProductOrderNo(), scProductOrder.getCustomerName(),
                            scProductOrder.getProductName(), scProductOrder.getCurrentNodeName()};
                    try {
                        sendMsg(scProductOrder, msg, "ZZSC_SC_NODE_ALERT");
                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.error("生产订单:" + scProductOrder.getScProductOrderNo() + ",节点预警消息发送失败！");
                    }
                }
            }
        }.start();
    }

    public void orderAlert() {
        List<String> statusArr = new ArrayList<>();
        statusArr.add("ZZSC_STATE_SCPROORDER_CODE1");
        statusArr.add("ZZSC_STATE_SCPROORDER_CODE2");
        statusArr.add("ZZSC_STATE_SCPROORDER_CODE3");
        statusArr.add("ZZSC_STATE_SCPROORDER_CODE4");
        statusArr.add("ZZSC_STATE_SCPROORDER_CODE5");
        statusArr.add("ZZSC_STATE_SCPROORDER_CODE6");
        statusArr.add("ZZSC_STATE_SCPROORDER_CODE14");
        //查询订单即将超期(订单办理截止时间小于15天)订单信息,
        List<ProductTimeStatus> scProductTimeStatusList = this.productTimeStatusDao.query(new HashMap<String,Object>() {{
            put("orderAlert", "true");
            put("statusArr",statusArr);
        }});
        if (scProductTimeStatusList.size() == 0) {
            return;
        }
        final List<Long> idList = new ArrayList<>(scProductTimeStatusList.size());
        Map<Long, ProductTimeStatus> scProductTimeStatusMap = new HashMap<>(scProductTimeStatusList.size());
        for (ProductTimeStatus scProductTimeStatus : scProductTimeStatusList) {
            idList.add(scProductTimeStatus.getId());
            scProductTimeStatusMap.put(scProductTimeStatus.getId(), scProductTimeStatus);
        }
        this.productTimeStatusDao.updateExpectOpenTimeStatus(ScProductConstant.TIME_OUT, idList);
        List<ProductOrder> scProductOrderList = this.productOrderDao.queryProductOrder(new HashMap<String,Object>() {{
            put("idInList", idList);
        }});
        new Thread() {
            public void run() {
                for (ProductOrder scProductOrder : scProductOrderList) {
                    ProductTimeStatus scProductTimeStatus = scProductTimeStatusMap.get(scProductOrder.getId());
                    if (scProductOrder.getFlowUserId() == null || scProductTimeStatus == null) {
                        continue;
                    }
                    //生产单号,客户名称,产品名称
                    try {
                        //即将超期时间
                        int day = DateUtil.daysBetween( new Date(),scProductTimeStatus.getOrderEndTime());
                        //办理时长
                        int day1 = DateUtil.daysBetween(scProductOrder.getCreateTime(), new Date());
                        String[] msg = new String[]{scProductOrder.getScProductOrderNo(), scProductOrder.getCustomerName(), scProductOrder.getProductName(),
                                String.valueOf(day1), String.valueOf(day)};
                        sendMsg(scProductOrder, msg, "ZZSC_SC_ORDER_ALERT");
                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.error("生产订单:" + scProductOrder.getScProductOrderNo() + ",订单预警消息发送失败！");
                    }
                }
            }
        }.start();
    }

    public void contractAlert() {
        List<String> statusArr = new ArrayList<>();
        statusArr.add("ZZSC_STATE_SCPROORDER_CODE1");
        statusArr.add("ZZSC_STATE_SCPROORDER_CODE2");
        statusArr.add("ZZSC_STATE_SCPROORDER_CODE3");
        statusArr.add("ZZSC_STATE_SCPROORDER_CODE4");
        statusArr.add("ZZSC_STATE_SCPROORDER_CODE5");
        statusArr.add("ZZSC_STATE_SCPROORDER_CODE6");
        statusArr.add("ZZSC_STATE_SCPROORDER_CODE14");
        //查询合同即将超期(合同截止时间小于15)订单信息,
        List<ProductTimeStatus> scProductTimeStatusList = this.productTimeStatusDao.query(new HashMap<String,Object>() {{
            put("contractAlert", "true");
            put("statusArr",statusArr);
        }});
        if (scProductTimeStatusList.size() == 0) {
            return;
        }
        final List<Long> idList = new ArrayList<>(scProductTimeStatusList.size());
        for (ProductTimeStatus scProductTimeStatus : scProductTimeStatusList) {
            idList.add(scProductTimeStatus.getId());
        }
        List<ProductOrder> scProductOrderList = this.productOrderDao.queryProductOrder(new HashMap<String,Object>() {{
            put("idInList", idList);
        }});
        new Thread(){
            public void run(){
                for (ProductOrder scProductOrder : scProductOrderList) {
                    if (scProductOrder.getFlowUserId() == null) {
                        continue;
                    }
                    try {
                        //生产单号,客户名称,产品名称
                        //即将超期时间
                        int day = DateUtil.daysBetween(new Date(),scProductOrder.getContractEndDate());
                        //办理时长
                        int day1 = DateUtil.daysBetween(scProductOrder.getCreateTime(),new Date());
                        String[] msg = new String[]{scProductOrder.getScProductOrderNo(),scProductOrder.getCustomerName(),
                                scProductOrder.getProductName(),String.valueOf(day1),String.valueOf(day)};
                        sendMsg(scProductOrder,msg,"ZZSC_SC_CONTRACT_ALERT");
                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.error("生产订单:"+scProductOrder.getScProductOrderNo()+",合同预警消息发送失败！");
                    }
                }
            }
        }.start();
    }

    /**
     * 证书入库即将超期提醒
     */
    public void zsOrderOverdueAlert() throws ParseException {
        List<ProductOrder> list = productOrderDao.selectZsorder();
        if(list.size()>0){
            for(ProductOrder productOrder : list){
                if (!StringUtils.isEmpty(productOrder.getFlowContent())) {
                    List<Node> nodeList = flowService.getNode(productOrder.getId());
                    if (nodeList.size() > 0) {
                        Node node = nodeList.get(0);
                        Date newDate = commonService.getDateFromStartByType(productOrder.getOrderTime(),
                                (int) Math.ceil(node.getHandleDate() / 24), (long) Math.ceil(node.getHandleDate() / 24) * 24 * 36000,
                                node.getIsNaturalorWorkday());
                        //还有一天即将超期
                        if (1 == DateUtil.daysBetween(new Date(), newDate)) {
                            //推送送消息
                            new Thread() {
                                //您好，{销售订单编号}{客户名称}{订单产品}证书还未入库，明天将超期，请及时跟踪处理！
                                public void run() {
                                    try {
                                        //证书管理员
                                        List<UserEntity> users = new ArrayList<>();
                                        String[] codes = new String[]{"ZZSC_ZS_ADMIN"};
                                        //签单商务
                                        UserEntity signUser = userService.findUserById(productOrder.getSignUserId());
                                        if (null != signUser) {
                                            users.add(signUser);
                                        }
                                        List<UserEntity> zsUsers = userService.findUserByRoleCodesAndOrgs(codes, 0, productOrder.getProductOrgId());
                                        if (zsUsers.size() > 0) {
                                            users.addAll(zsUsers);
                                        }
                                        String[] msg = new String[]{productOrder.getScProductOrderNo(), productOrder.getCustomerName(),
                                                productOrder.getProductName()};
                                        commonService.sendMsg(users, msg, "ZZSC_ZS_RK_SOON");
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        logger.error("生产订单:" + productOrder.getScProductOrderNo() + ",证书入库即将超期提醒消息发送失败！");
                                    }

                                }
                            }.start();
                        }
                    }
                }
            }
        }
    }
    /**
     * 证书入库超期提醒
     */
    public void zsOrderOverAlert(){
        List<ProductOrder> list = productOrderDao.selectZsorder();
        if(list.size()>0){
            for(ProductOrder productOrder : list) {
                if (!StringUtils.isEmpty(productOrder.getFlowContent())) {
                    List<Node> nodeList = flowService.getNode(productOrder.getId());
                    if (nodeList.size() > 0) {
                        Node node = nodeList.get(0);
                        Date newDate = commonService.getDateFromStartByType(productOrder.getOrderTime(),
                                (int) Math.ceil(node.getHandleDate() / 24), (long) Math.ceil(node.getHandleDate() / 24) * 24 * 36000,
                                node.getIsNaturalorWorkday());
                        //还有一天即将超期
                        if (newDate.getTime() < new Date().getTime()) {
                            //推送送消息
                            new Thread() {
                                //您好，{销售订单编号}{客户名称}{订单产品}证书还未入库，明天将超期，请及时跟踪处理！
                                public void run() {
                                    try {
                                        //证书管理员
                                        List<UserEntity> users = new ArrayList<>();
                                        String[] codes = new String[]{"ZZSC_ZS_ADMIN"};
                                        //签单商务
                                        UserEntity signUser = userService.findUserById(productOrder.getSignUserId());
                                        if (null != signUser) {
                                            users.add(signUser);
                                        }
                                        List<UserEntity> zsUsers = userService.findUserByRoleCodesAndOrgs(codes, 0, productOrder.getProductOrgId());
                                        if (zsUsers.size() > 0) {
                                            users.addAll(zsUsers);
                                        }
                                        int days = DateUtil.daysBetween(newDate, new Date())+1;
                                        String[] msg = new String[]{productOrder.getScProductOrderNo(), productOrder.getCustomerName(),
                                                productOrder.getProductName(), String.valueOf(days)};
                                        commonService.sendMsg(users, msg, "ZZSC_ZS_RK_OVER");
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        logger.error("生产订单:" + productOrder.getScProductOrderNo() + ",证书入库即将超期提醒消息发送失败！");
                                    }

                                }
                            }.start();
                        }
                    }
                }
            }
        }
    }

    public void certificateMatchFailedSendMsg() {
        List<ProductOrder> scProductOrderList = new ArrayList<>();
        new Thread(){
            public void run(){
                for (ProductOrder scProductOrder : scProductOrderList) {
                    if (scProductOrder.getFlowUserId() == null) {
                        continue;
                    }
                    try {
                        //生产单号,客户名称,产品名称
                        //即将超期时间
                        int day = DateUtil.daysBetween(new Date(),scProductOrder.getContractEndDate());
                        //办理时长
                        int day1 = DateUtil.daysBetween(scProductOrder.getCreateTime(),new Date());
                        String[] msg = new String[]{scProductOrder.getScProductOrderNo(),scProductOrder.getCustomerName(),
                                scProductOrder.getProductName(),String.valueOf(day1),String.valueOf(day)};
                        sendMsg(scProductOrder,msg,"ZZSC_SC_CONTRACT_ALERT");
                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.error("生产订单:"+scProductOrder.getScProductOrderNo()+",合同预警消息发送失败！");
                    }
                }
            }
        }.start();
    }
}
